package cn.xxstudy.visitshop.ui.activity.main.fragment.home

import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.adapter.InfoAdapter
import cn.xxstudy.visitshop.adapter.TaskAdapter
import cn.xxstudy.visitshop.base.fragment.LazyFragment
import cn.xxstudy.visitshop.util.configAppearance
import cn.xxstudy.visitshop.util.titleCenter
import cn.xxstudy.visitshop.ui.activity.main.fragment.home.viewmodel.HomeViewModel
import cn.xxstudy.visitshop.ui.activity.main.fragment.home.viewmodel.HomeViewModelFactory
import cn.xxstudy.visitshop.ui.activity.main.fragment.home.viewmodel.RefreshState
import kotlinx.android.synthetic.main.fragment_home.*

/**
 * @author ：DELL on 2021/3/23 .
 * @packages cn.xxstudy.visitshop.ui.activity.main.fragment.home
 * @TODO: 首页
 */
class HomeFragment : LazyFragment(), SwipeRefreshLayout.OnRefreshListener {

    private lateinit var viewModel: HomeViewModel
    override val layoutId = R.layout.fragment_home

    override fun initView() {
        titleToolbar.titleCenter()
        newTaskContent.configAppearance(context)
        newInfoContent.configAppearance(context)
        homeRefresh.setOnRefreshListener(this)
        homeRefresh.configAppearance()
    }

    override fun loadData() {
        viewModel =
            ViewModelProvider(this, HomeViewModelFactory()).get(HomeViewModel::class.java)
        viewModel.bannerLiveData.observe(viewLifecycleOwner, Observer {
            banner.setAdapterData(it)
        })


        val taskAdapter = TaskAdapter()
        newTaskContent.adapter = taskAdapter
        viewModel.taskLiveData.observe(viewLifecycleOwner, Observer {
            taskAdapter.datas = it
        })


        val infoAdapter = InfoAdapter()
        newInfoContent.adapter = infoAdapter
        viewModel.infoLiveData.observe(viewLifecycleOwner, Observer {
            infoAdapter.datas = it
        })

        viewModel.failLiveData.observe(viewLifecycleOwner, Observer {
            Toast.makeText(context, it, Toast.LENGTH_SHORT).show()
        })

        viewModel.refreshState.observe(viewLifecycleOwner, Observer {
            when (it) {
                RefreshState.START -> homeRefresh.isRefreshing = true
                RefreshState.COMPLETE -> homeRefresh.isRefreshing = false
            }
        })

        homeRefresh.post {
            homeRefresh.isRefreshing = true
            viewModel.refresh()
        }

        lifecycle.addObserver(banner)
    }

    override fun onRefresh() {
        viewModel.refresh()
    }


}